package com.infore.dataAudit.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.infore.dataAudit.entity.TEvidenceFile;
import com.infore.dataAudit.enums.AuditStatus;
import com.infore.dataAudit.repository.ITEvidenceRepository;
import com.infore.dataAudit.service.audit.IDataAuditService;
import com.infore.dataAudit.util.Constants;
import com.infore.dataAudit.util.CookiesUtil;
import com.infore.dataAudit.util.ResultEntity;
import com.infore.dataAudit.vo.AuditRecordQuery;
import com.infore.dataAudit.vo.CustomerDataAuditVO;
import com.infore.dataAudit.vo.DataAuditVO;
import com.infore.dataAudit.vo.StatisAuditDateVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "数据审核服务", tags = "数据审核服务")
@RestController
@RequestMapping("/dataAudit")
public class DataAuditController {
   
    @Autowired
    private IDataAuditService dataAuditService;
    @Autowired
    private ITEvidenceRepository evidenceRepository;
    
    @ApiOperation(value = "查询审核数据", notes = "查询某监测时间段内的审核数据")
    @RequestMapping(value = "/queryAuditData", method= RequestMethod.GET)
    public ResultEntity queryAuditDataByTimeAndMn(@RequestParam(required = true) String startTime,
            @RequestParam(required = true) String endTime, @RequestParam(required = true) String mn) {
        return dataAuditService.queryAuditDataByTimeAndMn(startTime, endTime, mn);
    }
    
    @ApiOperation(value = "查询图形审核数据", notes = "查询图形某监测时间段内的审核数据")
    @RequestMapping(value = "/queryEchartsAuditData", method= RequestMethod.GET)
    public ResultEntity queryEchartsAuditDataByTimeAndMn(@RequestParam(required = true) String startTime,
            @RequestParam(required = true) String endTime, @RequestParam(required = true) String mn) {
        return dataAuditService.queryEchartsAuditDataByTimeAndMn(startTime, endTime, mn);
    }
    
    @RequestMapping(value = "/save", method= RequestMethod.GET)
    public ResultEntity testSave() {
        return dataAuditService.saveTDataAudit(null);
    }
    
    /**
     * 查询操作记录 某流程
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param flowId 流程实例id
     * @return
     * @date 2019年5月7日下午4:58:45
     */
    @ApiOperation(value = " 查询操作记录 某流程", notes = " 查询操作记录 某流程")
    @RequestMapping(value = "/auditOperaRecord", method= RequestMethod.GET)
    public ResultEntity queryAuditOperaRecordByFlow(@RequestParam("flowId")String flowId) {
        return dataAuditService.queryAuditOperaRecordByFlow(flowId);
    }
    
    /**
     * 审核数据 人工审核
     * 数据标记 有效无效标记
     * @author 蔡永顺
     * @return ResultEntity
     * @param vo 审核数据 用户  流程实例id....
     * @return
     * @date 2019年4月18日下午7:14:51
     */
    @ApiOperation(value = "审核数据 人工审核", notes = "审核数据 人工审核")
    @RequestMapping(value = "/auditCustomer", method= RequestMethod.POST)
    public ResultEntity auditCustomer(@RequestBody DataAuditVO vo, HttpServletRequest request) {
       // System.out.println(list.get(0).get("监测时间") + "===============");
       // String platformId = CookiesUtil.getCookieValue(request, "platformId");
        String userId = CookiesUtil.getCookieValue(request, "userId");
        vo.setUserId(userId);
        String appCode = CookiesUtil.getCookieValue(request, "appCode");
        return dataAuditService.auditCustomer(vo, appCode);
    }
    
    /**
     * 提交审核 完成任务
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param vo
     * @return
     * @date 2019年5月7日下午2:13:27
     */
    @ApiOperation(value = "提交审核 完成任务", notes = "提交审核 完成任务")
    @RequestMapping(value = "/auditCustomerTask", method= RequestMethod.POST)
    public ResultEntity auditCustomerTask(@RequestBody CustomerDataAuditVO vo, HttpServletRequest request) {
       // System.out.println(list.get(0).get("监测时间") + "===============");
        String appCode = CookiesUtil.getCookieValue(request, "appCode");
        String userId = CookiesUtil.getCookieValue(request, "userId");
        vo.setUserId(userId);
        return dataAuditService.auditCustomerTask(vo, appCode);
    }
    
    /**
     * 驳回
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param date 日期 yyyy-MM-dd
     * @param userId
     * @param reviewPass 1 一级审核 2 二级审核  0 都驳回
     * @param comment
     * @return
     * @date 2019年5月17日下午3:31:54
     */
    @ApiOperation(value = "驳回", notes = "驳回")
    @RequestMapping(value = "/rejectDataAudit", method= RequestMethod.GET)
    public ResultEntity rejectDataAudit(@RequestParam("mn")String mn, @RequestParam("date")String date,
                @RequestParam("userId")String userId
                ,@RequestParam("reviewPass")Integer reviewPass,@RequestParam("comment")String comment) {
        return dataAuditService.rejectDataAudit(mn, date, userId, reviewPass,comment);
    }
    
    
    /**
     * 查询审核记录
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param query
     * @return
     * @date 2019年4月20日上午10:31:26
     */
    @ApiOperation(value = "查询审核记录", notes = "查询审核记录")
    @RequestMapping(value = "/dataAuditRecordPage", method= RequestMethod.POST)
    public ResultEntity queryDataAuditRecordPage(@RequestBody AuditRecordQuery query) {
        return dataAuditService.queryDataAuditRecordPage(query);
    }
    
    /**
     * 无效数据统计
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param query
     * @return
     * @date 2019年5月9日下午3:34:45
     */
    @ApiOperation(value = "无效数据统计", notes = "无效数据统计")
    @RequestMapping(value = "/invalideDataAuditPage", method= RequestMethod.POST)
    public ResultEntity queryInValideDataAuditStatisPage(@RequestBody AuditRecordQuery query) {
        return dataAuditService.queryDataAuditDetailStatisPage(query, AuditStatus.INVALIDE.getStatusCode());
    }
    
    /**
     * 存疑数据统计
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param query
     * @return
     * @date 2019年5月9日下午3:35:38
     */
    @ApiOperation(value = "存疑数据统计", notes = "存疑数据统计")
    @RequestMapping(value = "/doubtataAuditPage", method= RequestMethod.POST)
    public ResultEntity queryDoubtataAuditStatisPage(@RequestBody AuditRecordQuery query) {
        return dataAuditService.queryDataAuditDetailStatisPage(query, AuditStatus.DOUBT.getStatusCode());
    }
    
    
    /**
     * 上传无效佐证文件
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param file
     * @return
     * @date 2019年5月6日上午11:42:55
     */
    @RequestMapping(value = "/saveEvidenceFile", method= RequestMethod.POST)
    public ResultEntity saveEvidenceFile(@RequestParam("file") MultipartFile file
            ,@RequestParam("userId") String userId, @RequestParam("dataId") String dataId) {
        return dataAuditService.saveEvidenceFile(file, userId, dataId);
    }
    
    /**
     * 统计站点某时间段内审核情况 当天审核与未审核日历
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param list
     * @return
     * @date 2019年5月21日下午3:07:41
     */
    @ApiOperation(value = "统计站点某时间段内审核情况 当天审核与未审核日历", notes = "统计站点某时间段内审核情况 当天审核与未审核日历")
    @RequestMapping(value = "/statisDataAudit", method= RequestMethod.POST)
    public ResultEntity statisDataAudit(@RequestBody List<StatisAuditDateVO> list) {
        return dataAuditService.statisDataAudit(list);
    }
    
    
    /**
     * 多站点 月份统计 审核未审核已审未审(驻站)
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param query
     * @return
     * @date 2019年5月21日下午3:08:01
     */
    @ApiOperation(value = "多站点 月份统计 审核未审核已审未审(驻站)", notes = "多站点 月份统计 审核未审核已审未审(驻站)")
    @RequestMapping(value = "/statisDataAuditByStationMns", method= RequestMethod.POST)
    public ResultEntity statisDataAuditByStationMns(@RequestBody AuditRecordQuery query) {
        return dataAuditService.statisDataAudit(query);
    }
    
    /**
     * 查询佐证文件
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param flowId
     * @return
     * @date 2019年5月21日下午3:18:14
     */
    @ApiOperation(value = "查询佐证文件", notes = "查询佐证文件")
    @RequestMapping(value = "/queryEvidenceFile", method= RequestMethod.GET)
    public ResultEntity queryEvidenceFile(@RequestParam("flowId")String flowId) {
        return dataAuditService.queryEvidenceFile(flowId);
    }
    
    @RequestMapping(value = "/downloadEvidenceFile", method= RequestMethod.GET)
    public void downloadEvidenceFile(@RequestParam("id")String id, HttpServletResponse response) throws IOException {
        TEvidenceFile evidence = evidenceRepository.findById(id).get();
        String error ="";
        if(evidence == null) {
            error = "佐证文件不存在!";
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write(error);
        }
        String filename = evidence.getFileName();
        try {
            File file = new File(Constants.BASE_PATH + evidence.getFilePath());
            // File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            byte[] bytes = bos.toByteArray();
            if (bytes != null) {
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
                response.addHeader("Content-Length", "" + bytes.length);
                response.setContentType("application/octet-stream;charset=utf-8");
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                toClient.write(bytes);
                toClient.flush();
                toClient.close();
            }
        } catch (FileNotFoundException e) {
            // e.printStackTrace();
            // filename = java.net.URLEncoder.encode(filename, "UTF-8");
            error = "文件不存在!!";
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write(error);
        } catch (Exception e) {
            e.printStackTrace();
            // filename = java.net.URLEncoder.encode(filename, "UTF-8");
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write(error);
        }
    }
}
